from typing import List, Union
from fastapi import APIRouter, Depends, Response, Query
from sqlalchemy.orm import Session
from datetime import datetime
from db import get_db, crud
from schemas.customer import CustomerModel
from schemas.flower import FlowerModel
from schemas.shopping_cart import CreateShoppingCartProductRequest, \
    UpdateShoppingCartProductQuantityRequest, ShoppingCartItem
from .customer import verify_customer_token

router = APIRouter(prefix="/customer/shopping-cart", tags=["购物车"])


@router.get("", response_model=List[ShoppingCartItem], response_model_exclude_none=True)
def get_shopping_cart(customer: CustomerModel = Depends(verify_customer_token),
                      db: Session = Depends(get_db)):
    data = crud.ShoppingCart.get_by_customer(db, customer.id)

    result = []

    for item in data:
        flower = FlowerModel.from_orm(item.flower)
        if flower.status == 1:
            result.append(ShoppingCartItem(
                id=item.id,
                quantity=item.quantity,
                flower=flower
            ))

    return result


@router.post("")
def add_product(data: CreateShoppingCartProductRequest,
                customer: CustomerModel = Depends(verify_customer_token),
                db: Session = Depends(get_db)):
    data.created_on = datetime.now()
    data.customer_id = customer.id
    return crud.ShoppingCart.create(db, data)


@router.delete("")
def delete_product(ids: Union[List[int], None] = Query(default=None, alias="id"),
                   customer: CustomerModel = Depends(verify_customer_token),
                   db: Session = Depends(get_db)):
    crud.ShoppingCart.delete_many(db, customer.id, ids)
    return Response()


@router.put("/quantity", dependencies=[Depends(verify_customer_token)])
def update_product_quantity(data: UpdateShoppingCartProductQuantityRequest,
                            db: Session = Depends(get_db)):
    data.updated_on = datetime.now()
    crud.ShoppingCart.update_quantity(db, data)
    return Response()
